package myarray;

import java.util.Arrays;

public class MyArray {

    private int[] data;
    private int size;
    // 存储元素仍然还在数组中存储
    public MyArray() {
        data = new int[10];
    }
    // 当前动态数组中实际存储的元素个数
    public MyArray(int dx) {
        data = new int[dx];
    }


    //1.增加元素
    //头插
    public void addFirst(int val){
        addIndex(0,val);
    }
    //尾插
    public void addLast(int val){
        addIndex(size,val);
    }
    //中间插值
    public void addIndex(int index,int val){
        //判断数组是否满
        if(size==data.length){
            grow();
        }
        //判断index是否合法
        if(index<0||index>size){
            System.out.println("add index illegal!");
            return;
        }
        else{
            //将index位置空出
            for (int i = size-1; i >= index; i--) {
                data[i+1]=data[i];
            }
            data[index]=val;
            size++;
        }
    }

    //查找元素
    //根据元素查找下标
    public int getValueIndex(int val){
        for (int i = 0; i < size; i++) {
            if(data[i]==val){
                return i;
            }
        }
        return -1;
    }
    //根据下标查找元素
    public int getIndexValue(int index){
        if(index<0||index>size){
            System.out.println("get index illegal!");
        }
        return data[index];
    }

    //改变元素
    public void change(int index,int val){
        if(index<0||index>size){
            System.out.println("get index illegal!");
        }
        data[index]=val;
    }

    //删除
    public void removeFirst(){
        removeIndex(0);
    }
    public void removeLast(){
        removeIndex(size-1);
    }
    public void removeIndex(int index){
        if(index<0||index>size){
            System.out.println("get index illegal!");
        }
        for (int i = index; i < size-1; i++) {
            data[i]=data[i+1];
        }
        size--;
        data[size]=0;
    }
    public void removeOneValue(int val){
        for (int i = 0; i < size; i++) {
            if(data[i]==val){
                removeIndex(i);
                return;
            }
        }
    }
    public void removeAllValue(int val){
        for (int i = 0; i < size; i++) {
            while(data[i]==val){
                removeIndex(i);
            }
        }
    }

    //判断数组中是否有次值
    public boolean isAbove(int val){
        for (int i = 0; i < size; i++) {
            if(data[i]==val){
                return true;
            }
        }
        return false;
    }


    //输出
    public String toString() {
        String ret = "[";
        // 遍历data数组
        for (int i = 0; i < size; i++) {
            ret += data[i];
            if (i != size - 1) {
                ret += ",";
            }
        }
        ret += "]";
        return ret;
    }

    //扩容
    private void grow(){
        int[] newData=Arrays.copyOf(this.data,this.data.length<<1);
        this.data=newData;
    }
}
